package com.allwees.bs.c.module.order.context.compute.strategy.coupon;

import com.allwees.bs.c.module.order.context.bo.CouponComputeBo;
import com.allwees.bs.c.module.order.context.bo.CouponComputeItemBo;
import com.allwees.bs.c.module.order.context.bo.UserCouponBo;
import com.allwees.bs.core.model.user.constant.ECouponDefType;
import com.allwees.core.common.util.MoneyUtil;

import java.math.BigDecimal;

/**
 * 折扣券
 */
public class CouponDiscountStrategy extends CouponStrategy {

    @Override
    public boolean isSupport(UserCouponBo coupon) {
        if (coupon == null) {
            return false;
        }
        return ECouponDefType.RATE.equals(coupon.getCouponType()) && coupon.getFaceValue() != null;
    }

    @Override
    public CouponComputeBo use(UserCouponBo coupon, CouponComputeBo computeBo) {

        BigDecimal discountedAmtProduct = MoneyUtil.mul(computeBo.getAmtProduct(), coupon.getFaceValue());
        //实付金额(加价后的商品金额)和最大优惠金额比较,超过最大优惠就按封顶优惠，否则按折扣率计算优惠价格
        if (coupon.getMaxDeductAmt() != null && MoneyUtil.sub(computeBo.getAmtProduct(), discountedAmtProduct).compareTo(coupon.getMaxDeductAmt()) > 0) {
            computeBo = CouponDeductStrategy.useDeductAmt(coupon.getMaxDeductAmt(), computeBo);
        } else {//按折扣率计算优惠价格
            computeBo = useRatioAmt(coupon.getFaceValue(), computeBo);
        }
        //商品优惠
        //computeBo.setAmtProductCoupon(MoneyUtil.sub(computeBo.getOriginalAmtProduct(), computeBo.getAmtProduct()));
        return computeBo;
    }

    public static CouponComputeBo useRatioAmt(BigDecimal ratio, CouponComputeBo computeBo) {

        BigDecimal amtProduct = BigDecimal.ZERO;
        BigDecimal amtProductDiscount = BigDecimal.ZERO;

        int length = computeBo.getItems().size();
        for (int i = 0; i < length; i++) {
            CouponComputeItemBo item = computeBo.getItems().get(i);
            BigDecimal temp = item.getAmtSku();
            //计算商品金额 -- mul(computeBo.getAmtProduct(), ratio) 是总优惠, sub(mul(computeBo.getAmtProduct(), ratio), amtProduct) 是最后一个商品的优惠
            item.setAmtSku(last(length, i) ? sub(mul(computeBo.getAmtProduct(), ratio), amtProduct) : mul(item.getAmtSku(), ratio));

            amtProduct = MoneyUtil.add(amtProduct, item.getAmtSku());

            //计算优惠
            //item.setAmtProductCoupon(MoneyUtil.sub(temp, item.getAmtSku()));
            item.setAmtProductDiscountSku(sub(temp,item.getAmtSku()));
            item.computeAmt();

            amtProductDiscount= MoneyUtil.add(amtProductDiscount,item.getAmtProductDiscountSku());
        }
        computeBo.setAmtProduct(amtProduct);
        computeBo.setAmtProductCoupon(amtProductDiscount);//加价后的商品优惠
        return computeBo.computeAmt();
    }
}
